<template>
  <div>
    <el-page-header
      v-if="!newsId"
      icon=""
      title="新闻管理"
      content="创建新闻"
    />
    <el-page-header
      v-else
      title="新闻管理"
      content="修改新闻"
      @back="handleBack()"
    />

    <el-card style="margin-top: 20px">
      <el-form
        ref="newsFormRef"
        :model="newsForm"
        :rules="newsFormRules"
        label-width="80px"
        class="demo-ruleForm"
        v-if="loaded"
      >
        <!-- 标题 -->
        <el-form-item label="标题" prop="title">
          <el-input v-model="newsForm.title" />
        </el-form-item>

        <!-- 内容 -->
        <el-form-item label="内容" prop="content">
          <WangEditor v-model="newsForm.content" />
        </el-form-item>

        <!-- 类别 -->
        <el-form-item label="类别" prop="category">
          <el-select
            v-model="newsForm.category"
            class="m-2"
            placeholder="Select"
            style="width: 100%"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <!-- 封面 -->
        <el-form-item label="封面" prop="cover">
          <Upload :avatar="newsForm.cover" @imgChange="handleUploadChange" />
        </el-form-item>

        <!-- 发布状态 -->
        <el-form-item label="发布状态" prop="isPublish">
          <el-tooltip effect="dark" :content="publishStateTip" placement="top">
            <el-switch
              v-model="newsForm.isPublish"
              :active-value="1"
              :inactive-value="0"
            >
            </el-switch>
          </el-tooltip>
        </el-form-item>

        <!-- 添加/编辑新闻 -->
        <el-form-item>
          <el-button type="primary" @click="submitForm()">确定</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import axios from "axios";
import WangEditor from "@/components/editor/WangEditor";
import Upload from "@/components/upload/Upload.vue";
import upload from "@/utils/upload";

const router = useRouter(); // 获取'全局的路由实例'
const route = useRoute(); // 获取'当前路由的状态'
const loaded = ref(false); // 页面数据是否加载完毕, 【true: 加载完毕; false: 加载中】
const pageHeaderContent = ref("");
// 新闻类别
const options = [
  { label: "最新动态", value: 1 },
  { label: "典型案例", value: 2 },
  { label: "通知公告", value: 3 },
];
const newsFormRef = ref();
const newsForm = reactive({
  title: "新闻标题：",
  content: "新闻内容：",
  category: 1, // 1 最新动态, 2典型案例 3 通知公告
  cover: "/images/defaultUserImg.png",
  file: null,
  isPublish: 0, // 0 未发布, 1 已发布
});
// 表单校验
const newsFormRules = reactive({
  title: [{ required: true, message: "请输入标题", trigger: "blur" }],
  content: [{ required: true, message: "请输入内容", trigger: "blur" }],
  category: [{ required: true, message: "请选择分类", trigger: "blur" }],
  cover: [{ required: true, message: "请上传图片", trigger: "blur" }],
});
// 根据 newsForm.isPublish 的值返回对应的提示文本
const publishStateTip = computed(() => {
  return newsForm.isPublish === 0 ? "当前设置：未发布" : "当前设置：发布";
});

// 每次选择完图片之后的回调
const handleUploadChange = (file) => {
  newsForm.cover = URL.createObjectURL(file);
  newsForm.file = file;
};

/**
 * 编辑页面
 * */
const newsId = ref(route.params?.newsId || null);
// 获取新闻详情信息
const getDetailData = async () => {
  await axios
    .get(`/adminapi/news/list/${newsId.value}`)
    .then((res) => {
      Object.assign(newsForm, res.data.data[0]);
    })
    .catch((error) => {
      console.error(error);
    });
  loaded.value = true;
};
// 后退
const handleBack = () => {
  router.back();
};

// 添加/编辑新闻的提交
const submitForm = () => {
  newsFormRef.value.validate(async (valid) => {
    if (!valid) return;
    if (!newsId.value) {
      await upload("/adminapi/news/add", newsForm);
      router.push(`/news-manage/newslist`);
    } else {
      const params = new FormData();
      for (let i in newsForm) {
        params.append(i, newsForm[i]);
      }
      await axios
        .put(`/adminapi/news/list/${newsId.value}`, params)
        .catch(() => {
          console.error(error);
        });
      router.back();
    }
  });
};

// 组件挂载后执行的钩子函数
onMounted(() => {
  if (newsId.value) {
    getDetailData();
  } else {
    loaded.value = true;
  }
});
</script>

<style lang="scss" scoped>
.el-form {
  margin-top: 20px;
}
</style>
